﻿using System;
using System.ComponentModel;
using System.Text.RegularExpressions;

namespace QA.TFS.Conditions
{
    [DisplayName("Find Text")]
    [Description("Searches the last response for the existence of the specified text.")]
    public class IfFindText : Microsoft.VisualStudio.TestTools.WebTesting.ConditionalRule
    {

        [DisplayName("Find Text")]
        [Description("The text to search for in the last response of the web test.")]
        public string Value { get; set; }

        [DisplayName("Ignore Case")]
        [Description("If true case is ignored while seaching for the string in the response.")]
        [DefaultValue(true)]
        public bool IgnoreCase { get; set; }

        [DisplayName("Use Regular Expression")]
        [Description("Use a regular expression during search.")]
        public bool UseRegularExpression { get; set; }

        [DisplayName("Pass If Text Found")]
        [Description("Condition passes if the text is found when this property is set true, or when the text is not found and this property is set false.")]
        [DefaultValue(true)]
        public bool PassIfNotFound { get; set; }

        [DisplayName("Stop Test If TextFound Condition is not Met")]
        [Description("Stops test if the Find Condition is not Met.")]
        [DefaultValue(false)]
        public bool StopOnFail { get; set; }

        /// <summary>
        /// Determines whether the condition was met or not.
        /// </summary>
        /// <param name="sender">The sender of the event.</param>
        /// <param name="e">The Microsoft.VisualStudio.TestTools.WebTesting.ConditionalEventArgs that contains the event data.</param>
        public override void CheckCondition(object sender, Microsoft.VisualStudio.TestTools.WebTesting.ConditionalEventArgs e)
        {
            if (UseRegularExpression)
            {
                Match result = Regex.Match(e.WebTest.LastResponse.BodyString, Value, IgnoreCase ? RegexOptions.IgnoreCase : RegexOptions.None);
                e.IsMet = result.Success;
            }
            else
            {
                int index = e.WebTest.LastResponse.BodyString.IndexOf(Value, IgnoreCase ? StringComparison.CurrentCultureIgnoreCase : StringComparison.CurrentCulture);
                e.IsMet = index == -1 ? false : true;
            }

            if (PassIfNotFound)
                e.IsMet = !e.IsMet;

            if (!e.IsMet && StopOnFail)
                e.WebTest.Stop();
        }
    }
}
